package com.airline.service;

import com.airline.entity.Aircraft;
import com.airline.entity.Flight;
import com.airline.repository.AircraftRepository;
import com.airline.repository.FlightRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
@Transactional
public class FlightService {
    private final FlightRepository flightRepository;
    private final AircraftRepository aircraftRepository;

    // 添加初始化方法
    public void initFlights() {
        // 检查是否已有数据
        if (flightRepository.count() > 0) {
            System.out.println("已有航班数据，跳过初始化");
            return;
        }

        // 创建飞机
        Aircraft aircraft = new Aircraft();
        aircraft.setTailNumber("B-1234");
        aircraft.setModel("Boeing 737");
        aircraft.setCapacity(180);
        aircraft.setStatus("ACTIVE");
        aircraftRepository.save(aircraft);

        // 创建航班
        Flight flight = new Flight();
        flight.setFlightNumber("CA1234");
        flight.setDepartureCity("北京");
        flight.setArrivalCity("上海");
        flight.setDepartureTime(LocalDateTime.now().plusDays(1));
        flight.setArrivalTime(LocalDateTime.now().plusDays(1).plusHours(2));
        flight.setAircraft(aircraft);
        flight.setEconomyPrice(new BigDecimal("800.00"));
        flight.setBusinessPrice(new BigDecimal("1500.00"));
        flight.setAvailableSeats(180);
        flightRepository.save(flight);

        System.out.println("航班数据初始化完成");
    }

    public List<Flight> searchFlights(String departureCity, String arrivalCity, LocalDateTime departureDate) {
        return flightRepository.findByDepartureCityAndArrivalCityAndDepartureTimeAfter(
                departureCity, arrivalCity, departureDate);
    }

    public List<Flight> getAllFlights() {
        return flightRepository.findAll();
    }

    public Optional<Flight> getFlightById(Long id) {
        return flightRepository.findById(id);
    }

    public Flight createFlight(Flight flight) {
        return flightRepository.save(flight);
    }
}